package com.example.homeworkhelper.userInfo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.homeworkhelper.R;
import com.example.homeworkhelper.faq.FaqActivity;
import com.example.homeworkhelper.feedback.FeedBackActivity;
import com.example.homeworkhelper.history.HistoryDisplayActivity;
import com.example.homeworkhelper.login.LoginMain;
import com.example.homeworkhelper.mainPage.MainPageActivity;
import com.example.homeworkhelper.userInfo.setting.SettingActivity;
import com.example.homeworkhelper.utils.common.Config;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UserInfoActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btnOpenHistory;
    private Button btnOpenSetting;
    private Button btnOpenHelp;
    private TextView tvName;
    private TextView tvRole;
    private TextView tvGrade;
    private TabLayout tabBtm;
    private Button btnFeedback;

    private class HttpResult {
        private UserDto data;

        private UserDto getDto() {
            return data;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        initButton();
//        initTab();
        initUserDto();
        refreshText();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        TabLayout.Tab tab1 = tabBtm.getTabAt(1);
//        tab1.select();
        refreshText();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
//        TabLayout.Tab tab1 = tabBtm.getTabAt(1);
//        tab1.select();
        refreshText();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_open_history:
                startActivity(new Intent(this, HistoryDisplayActivity.class));
                break;
            case R.id.btn_open_setting:
            case R.id.layout_user_info:
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.id.btn_open_help:
                startActivity(new Intent(this, FaqActivity.class));
                break;
            case R.id.btn_open_feedback:
                startActivity(new Intent(this, FeedBackActivity.class));
                break;
        }
    }

//    private void initTab() {
//        tabBtm = findViewById(R.id.user_info_tabs);
//        TabLayout.Tab tabHome = tabBtm.getTabAt(0);
//        TabLayout.Tab tabUserInfo = tabBtm.getTabAt(1);
//        tabUserInfo.select();
//        tabBtm.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
//            @Override
//            public void onTabSelected(TabLayout.Tab tab) {
//                if (tab == tabHome) {
//                    startNewActivity(MainPageActivity.class);
//                }
//            }
//
//            @Override
//            public void onTabUnselected(TabLayout.Tab tab) {
//
//            }
//
//            @Override
//            public void onTabReselected(TabLayout.Tab tab) {
//
//            }
//        });
//    }

    private void initButton() {
        View userInfoLayout = findViewById(R.id.layout_user_info);
        userInfoLayout.setOnClickListener(this);

        btnOpenHistory = findViewById(R.id.btn_open_history);
        btnOpenSetting = findViewById(R.id.btn_open_setting);
        btnOpenHelp = findViewById(R.id.btn_open_help);
        btnFeedback = findViewById(R.id.btn_open_feedback);

        btnOpenHistory.setOnClickListener(this);
        btnOpenHelp.setOnClickListener(this);
        btnOpenSetting.setOnClickListener(this);
        btnFeedback.setOnClickListener(this);
    }

    private void startNewActivity(Class<?> cl) {
        startActivity(new Intent(this, cl));
    }

    private void refreshText() {
        UserDto userDto = readCacheDto();
        tvName = findViewById(R.id.text_name);
        tvName.setText(userDto.getU_name());
        tvRole = findViewById(R.id.text_role);
        tvGrade = findViewById(R.id.text_grade);

        tvRole.setVisibility(View.GONE);
        if (userDto.getGrade() != null) {
            tvRole.setVisibility(View.VISIBLE);
            switch (userDto.getRole_id()) {
                case 0:
                    userDto.setRole_name("教师");
                    break;
                case 1:
                    userDto.setRole_name("家长");
                    break;
                case 2:
                    userDto.setRole_name("学生");
                    break;
            }
            tvRole.setText(userDto.getRole_name());
            tvGrade.setText(userDto.getGrade());
        } else {
            tvGrade.setText("请设置身份信息");
        }
    }

    private void initUserDto() {
        SharedPreferences sharedPreferences = getSharedPreferences("userInfor", Context.MODE_PRIVATE);
        String user = sharedPreferences.getString("userDto", null);
        Gson gson = new Gson();
        String u_id = gson.fromJson(user,UserDto.class).getU_id();

        System.out.println("++++++++++++++++++++++++++++++"+u_id);
        if (u_id == null) {
            startActivity(new Intent(this, LoginMain.class));
        } else {
            postGetUserInfo();
        }
    }

    String res;

    private void postGetUserInfo() {
        SharedPreferences sharedPreferences = getSharedPreferences("userInfor", Context.MODE_PRIVATE);
        String user = sharedPreferences.getString("userDto", null);
        Gson gson = new Gson();
        String u_id = gson.fromJson(user,UserDto.class).getU_id();
        String url = Config.HttpUrlHead + "/user_info/get";
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()    //构建body
                .add("u_id", u_id).build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    Response response = okHttpClient.newCall(request).execute();
                    res = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
        try {
            t.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpResult data = gson.fromJson(res, HttpResult.class);
        UserDto test;
        try{
             test = data.getDto();
        }catch (NullPointerException e){
            Thread t1 = new Thread() {
                @Override
                public void run() {
                    try {
                        Response response = okHttpClient.newCall(request).execute();
                        res = response.body().string();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            };
            t1.start();
            try {
                t1.join();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            data = gson.fromJson(res, HttpResult.class);
            test = data.getDto();
        }
        writeCacheDto(test);
    }

    private UserDto readCacheDto() {
        UserDto dto;
        SharedPreferences sharedPreferences = getSharedPreferences("userInfor", Context.MODE_PRIVATE);
        System.out.println("========================="+sharedPreferences.getBoolean("isLogin", false));
        if ( sharedPreferences.getBoolean("isLogin", false)) {
            Map userJson = sharedPreferences.getAll();
            Gson gson = new Gson();
            String nJson = gson.toJson(userJson);
            dto = gson.fromJson(nJson, UserDto.class);
        } else {
            dto = new UserDto();
            dto.setU_id("-1");
            writeCacheDto(dto);
        }
        return dto;

    }

    private void writeCacheDto(UserDto userDto) {
        SharedPreferences sharedPreferences = getSharedPreferences("userInfor", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("u_name", userDto.getU_name());
        editor.putString("u_avatar", userDto.getU_avatar());
        editor.putString("gender", userDto.getGender());
        editor.putString("role_name", userDto.getRole_name());
        editor.putString("phone", userDto.getPhone());
        editor.putString("grade", userDto.getGrade());
        editor.putString("u_id", userDto.getU_id());
        editor.putInt("role_id", userDto.getRole_id());
        editor.commit();
    }
}